package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1",6666))){
            while (! socketChannel.finishConnect()){
                System.out.println("连接需要时间,客户端不会阻塞,可以干其他工作");
            }
        }


        // 获取一个和str同样大小的buf
        //ByteBuffer buf = ByteBuffer.wrap(str.getBytes());


        ByteBuffer buf = ByteBuffer.allocate(1024);


        Scanner scanner = new Scanner(System.in);

        while (true){
            String s = scanner.next();
            buf.rewind();
            buf.clear();
            buf.put(s.getBytes());
            socketChannel.write(buf);
        }
    }
}
